package com.yaoweigroup.community.ui.home;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.adapter.BBSAdapter;
import com.yaoweigroup.community.adapter.BBSTitleAdapter;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.enity.BBSContent;
import com.yaoweigroup.community.enity.BBSTitle;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.UtilHttp;

/**
 * 邻里圈 主页
 * 
 * @author xi
 * 
 */
public class BBSMainActivity extends Activity implements OnClickListener {

	private RelativeLayout left_rl;
	private ListView listView;
	private TextView right_tv;
	private List<BBSContent> list;
	private BBSAdapter adapter;

	private ObjectMapper mapper;
	private TextView center_tv;
	private ProgressBar progress;

	private ImageView error_iv;
	private BBSTitle currentTitle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bbs_main);

		error_iv = (ImageView) findViewById(R.id.error_iv);
		progress = (ProgressBar) findViewById(R.id.progress);
		titles = new ArrayList<BBSTitle>();
		titleAdapter = new BBSTitleAdapter(this, titles);
		mapper = new ObjectMapper();
		list = new ArrayList<BBSContent>();
		adapter = new BBSAdapter(this, list);
		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);
		listView = (ListView) findViewById(R.id.listView);

		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setOnClickListener(this);
		right_tv = (TextView) findViewById(R.id.right_tv);
		right_tv.setOnClickListener(this);

		listView.setAdapter(adapter);

		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View vPopWindow = inflater
				.inflate(R.layout.pop_view, null, false);
		titlesView = (ListView) vPopWindow.findViewById(R.id.titlesView);
		titlesView.setAdapter(titleAdapter);
		progress_title = (ProgressBar) vPopWindow
				.findViewById(R.id.progress_title);
		popWindow = new PopupWindow(vPopWindow, 300, 600, true);
		popWindow.setBackgroundDrawable(new BitmapDrawable());
		popWindow.setFocusable(true);
		popWindow.setOutsideTouchable(true);
		titlesView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				popWindow.dismiss();
				currentTitle = titles.get(arg2);
				center_tv.setText(titles.get(arg2).getName());
				list.clear();
				progress.setVisibility(View.VISIBLE);
				error_iv.setVisibility(View.GONE);
				obtainTypeDetail(titles.get(arg2).getId());
			}
		});
		obtainType();

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Intent intent = new Intent(BBSMainActivity.this,
						PostDetailActivity.class);
				intent.putExtra("detail", list.get(position));
				startActivity(intent);
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		list.clear();
		if (currentTitle != null) {
			obtainTypeDetail(currentTitle.getId());
		}
	}

	private Intent intent;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_rl:
			finish();
			break;
		case R.id.right_tv:
			intent = new Intent(this, PostEditActivity.class);
			intent.putExtra("titles", currentTitle);
			startActivity(intent);
			break;
		case R.id.center_tv:
			showPopWindow(this, center_tv);
			break;
		}
	}

	public final int TYPE_SUCCESS = 0x2210;
	public final int TYPE_FAIL = TYPE_SUCCESS + 1;
	public final int DETAIL_SUCCESS = TYPE_SUCCESS + 2;
	public final int DETAIL_FAIL = TYPE_SUCCESS + 3;
	private List<BBSTitle> titles;

	private void obtainType() {

		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getsection, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							if (state == 200) {
								titles = mapper.readValue(data,
										new TypeReference<List<BBSTitle>>() {
										});
								handler.sendEmptyMessage(TYPE_SUCCESS);
							} else {
								handler.sendEmptyMessage(TYPE_FAIL);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(TYPE_FAIL);
							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(TYPE_FAIL);

					}

				});
	}

	private List<BBSContent> contents;

	private void obtainTypeDetail(int typeId) {
		error_iv.setVisibility(View.GONE);
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("typeid", typeId);
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getpostlist, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							if (state == 200) {
								contents = mapper.readValue(data,
										new TypeReference<List<BBSContent>>() {
										});
								handler.sendEmptyMessage(DETAIL_SUCCESS);
							} else {
								handler.sendEmptyMessage(DETAIL_FAIL);

							}
						} catch (Exception e) {
							handler.sendEmptyMessage(DETAIL_FAIL);

							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(DETAIL_FAIL);

					}

				});
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case TYPE_SUCCESS:
				progress_title.setVisibility(View.GONE);
				if (titles != null && titles.size() > 0) {
					titleAdapter.setDataChange(titles);
					currentTitle = titles.get(0);
					obtainTypeDetail(titles.get(0).getId());
				}
				break;
			case TYPE_FAIL:
				progress_title.setVisibility(View.GONE);
				break;
			case DETAIL_SUCCESS:
				progress.setVisibility(View.GONE);
				if (contents != null && contents.size() > 0) {
					list.addAll(contents);
					adapter.setDataChange(list);
				}
				if (list.size() == 0) {
					error_iv.setVisibility(View.VISIBLE);
					Toast.makeText(BBSMainActivity.this, "该版块没数据，赶快去灌水吧!", 500)
							.show();
				}
				break;
			case DETAIL_FAIL:
				progress.setVisibility(View.GONE);
				break;

			}
		};
	};

	private PopupWindow popWindow;
	private ListView titlesView;
	private BBSTitleAdapter titleAdapter;

	private ProgressBar progress_title;

	private void showPopWindow(Context context, View parent) {

		popWindow.showAtLocation(parent, Gravity.TOP, 60, 140);
	}

}
